package com.wally.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TimeClientHandler extends ChannelHandlerAdapter {

	private int counter;
	
	private byte[] req;
	
	private static final int MSG_SIZE = 100;
	
	public TimeClientHandler() {
		req = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {// 当客户端和服务端TCP链路建立成功之后，Netty的NIO线程会调用channelAction方法，
		// 发送查询时间的指令给服务端，调用writeAndFlush方法将请求消息发送给服务端
		ByteBuf message = null;
		for (int i = 0; i < MSG_SIZE; i++) {
			message = Unpooled.buffer(req.length);
			message.writeBytes(req);
			ctx.writeAndFlush(message);
		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//当服务端返回应答消息时，channelRead方法被调用
		ByteBuf buf = (ByteBuf) msg;// 从Netty的ByteBuf中读取并打印应答消息
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		log.info("Now is : {}; the counter is : {}", body, ++counter);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// 当发生异常时，打印异常日志，释放客户端资源
		log.warn("Unexpected exception from downstream : {}", cause.getMessage());
		ctx.close();
	}

}
